<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>WebSocket示例</title>
</head>
<body>
	<h1 style="text-align: center">WebSocket示例</h1>
	<div class="wrap">
		<div><textarea style="width:100%;height:450px" id="textShow" readonly></textarea></div>
		<p>内容：</p>
		<div style="text-align:center">
			<textarea style="width:100%;height:100px" id="textInput" placeholder="回车发送，shift+回车换行"></textarea>
			<button id="btnSend">发送</button>
		</div>
	</div>
	<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
	<script>
        // var wsUrl = 'ws://jigou2.he4966.cn:8081/ws'; // 修改为你的地址
		var wsUrl = 'ws://smile.wxnyxx.com:8080/im?_token=2865a094-ce07-48ce-808e-2c80a2330389';
		function getNowFormatDate() {
			var date = new Date();
			var seperator1 = "-";
			var seperator2 = ":";
			var month = date.getMonth() + 1;
			var strDate = date.getDate();
			if (month >= 1 && month <= 9) {
				month = "0" + month;
			}
			if (strDate >= 0 && strDate <= 9) {
				strDate = "0" + strDate;
			}
			var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
				+ " " + date.getHours() + seperator2 + date.getMinutes()
				+ seperator2 + date.getSeconds();
			return currentdate;
		}
		function fuckXSS(val) {
			var s = "";
			if(val.length == 0) return "";
			s = val.replace(/&/g,"&amp;");
			s = s.replace(/</g,"&lt;");
			s = s.replace(/>/g,"&gt;");
			s = s.replace(/ /g,"&nbsp;");
			s = s.replace(/\'/g,"&#39;");
			s = s.replace(/\"/g,"&quot;");
			return s;
		};
		
		var messageCache = [];

		messageCache.push("Connecting...\r\n");
		var ws = new WebSocket(wsUrl);
 
		ws.onopen = function(evt) {
			console.log(evt)
			messageCache.push("Connection open\r\n\r\n");
			// sendContent2('{"action":"im.joinSysRoom"}');
		};

		ws.onmessage = function(evt) {
			messageCache.push(getNowFormatDate() + "\r\n" + fuckXSS(evt.data.substring(0, 128)) + "\r\n\r\n");
		};

		setInterval(function(){
			if(0 === messageCache.length)
			{
				return;
			}
			var message = messageCache.join("\r\n");
			messageCache = [];
			if($('#textShow').text().length >= 512 * 1024)
			{
				$('#textShow').text("消息过多，已清屏\r\n");
			}

			if(message.length > 512 * 1024)
			{
				$('#textShow').append("瞬时消息过大，不显示……\r\n");
				return;
			}

			var isScroll = $('#textShow').innerHeight() + $('#textShow').scrollTop() === $('#textShow')[0].scrollHeight

			$('#textShow').append(decodeUnicode(message));//中文解码

			if(isScroll)
			{
				$('#textShow').scrollTop($('#textShow')[0].scrollHeight);
			}
		}, 100); // 每100毫秒写入一次聊天记录
		
		ws.onclose = function(evt) {
			messageCache.push("Connection closed\r\n");
			int=window.clearInterval(int)
		};

		function sendContent()
		{
			var message = $('#textInput').val();
			if(message === '')
			{
				return;
			}
			// 发送
			var data = {
				action: 'send',
				message: message,
			};
			console.log(message);
			ws.send(message);
			// ws.send(JSON.stringify(data));
			$('#textInput').focus().val('');
		}

		function sendContent2(message)
		{
			
			if(message === '')
			{
				return;
			}
			// 发送
			var data = {
				action: 'send',
				message: message,
			};
			console.log(message);
			ws.send(message);
			// ws.send(JSON.stringify(data));
			$('#textInput').focus().val('');
		}

		$('#btnSend').click(sendContent);
		$('#textInput').on('keydown', function(e){
			if(e.keyCode == 13 && (!e.altKey && !e.ctrlKey && !e.shiftKey))
			{
				// 避免回车键换行
				e.preventDefault();
				// 下面写你的发送消息的代码
				sendContent();
			}
		})



		$('#btnSend').click(sendContent);
		$('#textInput').on('keydown', function(e){
			if(e.keyCode == 13 && (!e.altKey && !e.ctrlKey && !e.shiftKey))
			{
				// 避免回车键换行
				e.preventDefault();
				// 下面写你的发送消息的代码
				sendContent();
			}
		})

		function sendContent2(id)
		{
			
			var message = $('#'+id).html();
            console.log(message);
			if(message === '')
			{
				return;
			}

			ws.send(message);
			// ws.send(JSON.stringify(data));
			// $('#textInput').focus().val('');
			
		}

		//定时器
		var s = 0;
		var int=self.setInterval("clock(s)",1000);
		function clock(s1)
		{
			// alert(s1);
			
			// var t = $('#clock').value();
			s = s1 + 1;
			$('#clock').val((s).toString());
			// console.log(s);
		// var d=new Date();
		// var t=d.toLocaleTimeString();
		// document.getElementById("clock").value=t;
		}


		// 解码  
		function decodeUnicode(str) {  
				str = str.replace(/\\/g, "%");
				//转换中文
				str = unescape(str);
					//将其他受影响的转换回原来
				str = str.replace(/%/g, "\\");
					//对网址的链接进行处理
				str = str.replace(/\\/g, "");
				return str;
			}

		

	</script>

	<style>
	.wrap{
		width: 1000px;
		margin: 0 auto;
	}
	</style>
	<input type="text" id="clock" value="0">
	<p>连接地址ws://smile.wxnyxx.com:8080/im?_token=2865a094-ce07-48ce-808e-2c80a2330389     token是会员登录后的token，如果没有登录会直接连接失败</p>
	<div>连接成功后加入系统房间，后面好推送系统消息：<p style="background-color: beige;" onclick="sendContent2('1')" id="1">{"action":"im.joinSysRoom"}</p></div>
	<div>加入班级房间<p style="background-color: beige;" onclick="sendContent2('1_1')" id="1_1">{"team_id":"1","action":"im.joinTeamRoom"}</p></div>
	<div>机构和平台才能推送班级系统消息：<p style="background-color: beige;" onclick="sendContent2('2')" id="2">{"team_id":"1","action":"im.pushteam","content":"班级消息11"}</p></div>
	<div>机构和平台才能推送班级系统消息：<p style="background-color: beige;" onclick="sendContent2('3')" id="3">{"roomId":1,"action":"im.push","content":"11113333"}</p></div>
	<div>机构和平台才能推送系统消息：<p style="background-color: beige;" onclick="sendContent2('4')" id="4">{"roomId":"com","action":"im.push","content":"44444"}</p></div>
	<div>用户发送消息给用户可以不用调 加入个人房间：<p style="background-color: beige;" onclick="sendContent2('5')" id="5">{"roomId":"com","action":"im.sendUserMsg","re_uid":"24","content":"wo是1111"}</p></div>
	<div>加入个人房间（接收某个人的消息：<p style="background-color: beige;" onclick="sendContent2('6')" id="6">{"action":"im.joinUserMsg","re_uid":"24"}</p></div>
	
</body>
</html>